const fs = require('fs')
const path = require('path')
const goodModel=require('../../models/webapp/good')
const cateModel=require('../../models/webapp/cate')
class goodController{
    static async getGoodList(ctx){
        let {cate,page,size,name}=ctx.request.query
        // console.log(ctx.request.query,'99999')
        // console.log(size,'88888')
        page=parseInt(page || 1) 
        size=parseInt(size || 10) 
        // console.log(ctx.request.query)
        const p={
            name: new RegExp(name, 'img'),
            cate: cate || ''
        }
        if(!p.cate) delete p.cate
        const total=await goodModel.find(p).count()
        // console.log(size,'00000000')
        const list=await goodModel.find(p).limit(size).skip((page-1)*size)
        ctx.body={err:0,msg:'success',data:{total,list}}

    }
    // 获取类别
    static async getCates(ctx){
        const list = await cateModel.find({})
        ctx.body = { err:0, msg:'success',data:{list}}
    }
    // 上传图片
    static async getImage(ctx){
        // 将其放到后端某地
        console.log(ctx.request)
        const file = ctx.request.files.good
        const readStream = fs.createReadStream(file.path)
        const filePath = `/cdn/${Date.now()}_${file.name}`
        const writeStream = fs.createWriteStream(path.resolve(__dirname, `../../public${filePath}`))
        await readStream.pipe(writeStream)
        // writeStream.on('close', fn)
        ctx.body = {err:0,msg:'success',data: {img: filePath}}
    }
    // 删除
    static async deleteGood(ctx){
      let {ids}=ctx.request.query
      let arr = ids.split(';').filter(e=>e)
      for (let i=0; i<arr.length; i++) {
        await goodModel.deleteOne({_id: arr[i]})
      }
      ctx.body = { err: 0, msg: 'success', data: {}}
    }
    // 查看详情
    static async GoodDetail(ctx){
      let { id }=ctx.request.query;
      const good=await goodModel.find({_id:id})
      ctx.body={err:0,msg:'success',data:{good}}
    }
    // 新增商品/修改商品
    static async addGoods(ctx){
        let { name, desc, img, price, cate, hot, id } = ctx.request.body
    // 数据校验
    const ele = {
      name,
      desc,
      price,
      cate,
      img: img || '',
      hot: hot || false
    }
    let info = null
    console.log(id,'id')
    if(id) {
      info = await goodModel.updateOne({_id:id}, ele)
    }else{
      info =await goodModel.insertMany([ele])
    }
    ctx.body = { err: 0, msg: 'success', data: { info }}
  }


}
module.exports = goodController